<?php
defined('IN_SYS') or die('Restricted Access');
require_once SYS_LIB_KERNEL . 'sys.exception.php';
class SYS {
	private static $portal = NULL;
	private static $page = NULL;
	private static $act;

	function __construct() {
		Page :: set('SYS_TIME_BEGIN', sys_get_microtime());
		Page :: filterRequest();

		self :: $portal = Page :: getRequest('portal', 'str');
		self :: $page = Page :: getRequest('page', 'str');

		if (IS_DEBUG && self :: $portal == '__phpinfo__') {
			phpinfo();
			die();
		}
		if (self :: $portal == '' || self :: $page == '') {
			throw new SysExceptionControl('Do not found PORTAL or PAGE');
		}
	}

	/**
	 * execute function
	 */
	static function dispatch() {
		$func = SYS_APPS_MODULES . self :: $portal . DS . self :: $page . 'Action.php';
		$actionName = self :: $page . 'Action';

		if (!file_exists($func)) {
			throw new SysExceptionControl('File not found: ' . $actionName . '.php');
		}

		require_once $func;
		if (!class_exists($actionName)) {
			throw new SysExceptionControl('Function not found: ' . $actionName);
		}

		// Set
		Page :: set('SYS_PORTAL', self :: $portal);
		Page :: set('SYS_PAGE', self :: $page);
		Page :: set('SYS_ACTION', $actionName);

		// Get session lastest
		Page :: set('SYS_LAST_SESSION', Page :: getSessionAll());

		// Decode Session
		Page :: decodeSession();

		self :: $act = new $actionName ();
		self :: $act->getLangsPublic();

		//set default template
		$default_tpl = SYS_APPS_VIEWER . 'templates' . DS . self :: $portal . DS . self :: $page . '.tpl';
		if (file_exists($default_tpl)) {
			self :: $act->tpl(self :: $page, self :: $portal);
		}

		// output html
		if (!method_exists(self :: $act, 'execute')) {
			throw new SysExceptionControl('Function not found: execute()');
		}
		$output = self :: $act->execute();
		Page :: pushInfoPage(self :: $act->getSpec(), self :: $act->action, self :: $act->tpl);

		if (self :: $act->hasLayout()) {
			$html = self :: $act->getLayout();
			$alias = array (
				'[[|DESCRIPTION|]]' => '',
				'[[|KEYWORDS|]]' => '',
				'[[|TITLE|]]' => '',
				'[[|INC_STATIC_HEADER|]]' => '',
				'[[|CONTENT|]]' => $output,
				'[[|INC_STATIC_FOOTER|]]' => '',
				
			);
			$html = strtr($html, $alias);
		} else {
			$html = $output;
		}

		if (STATIC_COMPRESS_TPL === TRUE) {
			require_once SYS_LIB_KERNEL . 'sys.minify.php';
			$objMinify = new SysMinify();
			$html = $objMinify->compress_html($html);
		}
		echo $html;
	}

	function __destruct() {
		Page :: set('SYS_TIME_END', sys_get_microtime());
		// write log sql
		if (LOG_SQL === true) {
			SysLogs :: writeLogSql();
		}

		// print debug
		if (IS_DEBUG) {
			require_once SYS_LIB_KERNEL . 'sys.debug.php';
			$debug = new SysDebug();
			$debug->printDebug();
		}
	}
}